﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MessageSystem.Default.infrastructure
{
    class allocator:memory
    {
        public static allocator Instance = new allocator();

        public override void create()
        {
            base.create();
            ptr_block = alloc_block();
	        alloc_pos  = 0;
        }

        public msg alloc_sized_msg(UInt32 size)
        {
            msg ret = null;

            adjust(size);
            ret = alloc_msg();
            ret.data = ptr_block.duplicate();
            ret.readpos = alloc_pos;
            ret.writepos = alloc_pos;
            ret.totalsize = size;
            alloc_pos += size;

            return ret;
        }

        private void adjust(UInt32 require_size)
        {
            if (ptr_block.buffer.Length - alloc_pos < require_size)
            {
                free_block(ptr_block);
                ptr_block = alloc_block();
                alloc_pos = 0;
            }
        }

        private block ptr_block;
        private UInt32 alloc_pos;
    }
}
